package com.boot2.core.web.websocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.security.Principal;
import java.util.Map;

/**
 * @author zhangweilin
 * @Description: 默认的websocket握手拦截器
 * @date 2019/9/24
 */
//@Component
public class AbstractHandshakeInterceptor implements HandshakeInterceptor {

    @Autowired(required = false)
    AbstractWebsocketPrincipal abstractWebsocketPrincipal;

    @Autowired
    WebSocketSessionManager webSocketSessionManager;

    /**
     * Invoked before the handshake is processed.
     *
     * @param request    the current request
     * @param response   the current response
     * @param wsHandler  the target WebSocket handler
     * @param attributes attributes from the HTTP handshake to associate with the WebSocket
     *                   session; the provided attributes are copied, the original map is not used.
     * @return whether to proceed with the handshake ({@code true}) or abort ({@code false})
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
//        ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        //获取token认证
//        String token = req.getServletRequest().getParameter("token");
        //解析token获取用户信息
//        if (null == abstractWebsocketPrincipal) {
//            return true;
//        }

        Principal user = abstractWebsocketPrincipal.getPrincipal(request,response,wsHandler,attributes);
        if (user == null) {   //如果token认证失败user为null，返回false拒绝握手
            return false;
        }
        //保存认证用户
        attributes.put("user", user);
        //user.getName()一般为userId
        webSocketSessionManager.online(user.getName());
        return true;
    }

    /**
     * Invoked after the handshake is done. The response status and headers indicate
     * the results of the handshake, i.e. whether it was successful or not.
     *
     * @param request   the current request
     * @param response  the current response
     * @param wsHandler the target WebSocket handler
     * @param exception an exception raised during the handshake, or {@code null} if none
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {


    }
}
